<template>
    <div class="app-container">
        <el-form @submit.native.prevent :model="queryParams" ref="queryForm"  :inline="true"
            v-show="showSearch">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入查询的内容" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" ref="refbut">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd"
                    v-hasPermi="['tenantManage:infoManage:add']">添加</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2"  @click="handleImport"
                    v-hasPermi="['tenantManage:infoManage:import']">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download"  @click="handleExport"
                    v-hasPermi="['tenantManage:infoManage:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" border :height="tableHeight" :data="tenantList"
            @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column label="序号" type="index" width="120" />
            <el-table-column label="注册单位" prop="registeredUnit" :show-overflow-tooltip="true" />
            <el-table-column label="注册人" prop="registeredPerson" :show-overflow-tooltip="true" />
            <el-table-column label="用户名" prop="userName" />
            <el-table-column label="是否是管理单位" prop="isManagerDept">
              <template slot-scope="scope">
                {{ scope.row.isManagerDept == 'true' ? '是' : '否' }}
              </template>
            </el-table-column>
          <el-table-column label="全宗号" prop="fondsCode" />
<!--            <el-table-column label="登录账号" prop="loginName" />-->
            <el-table-column label="描述" prop="remark" />
            <el-table-column label="状态" align="state">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.state" active-value="0" inactive-value="1"
                        @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['tenantManage:infoManage:edit']">修改</el-button>
                    <el-button  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['tenantManage:infoManage:delete']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="45%" style="margin-top:8%" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="注册单位：" prop="registeredUnit">
                            <el-input v-model="form.registeredUnit" placeholder="请输入注册单位" />
                        </el-form-item></el-col>
                    <el-col :span="12"> <el-form-item label="注册人：" prop="registeredPerson">
                            <el-input v-model="form.registeredPerson" placeholder="请输入注册人" />
                        </el-form-item></el-col>
                </el-row>
                <el-row>
                    <el-col :span="12"> <el-form-item label="用户名：" prop="userName">
                            <el-input v-model="form.userName" placeholder="请输入用户名" />
                        </el-form-item></el-col>
                  <el-col :span="12">
                    <el-form-item label="是否管理单位：" prop="isManagerDept">
                      <el-select v-model="form.isManagerDept" placeholder="请选择" style="width: 100%">
                        <el-option label="是" value="true" />
                        <el-option label="否" value="false" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                    <!--
                    <el-col :span="12">
                      <el-form-item label="登录账号：" prop="loginName">
                            <el-input v-model="form.loginName" placeholder="请输入登录账号" />
                      </el-form-item>
                    </el-col>
                    -->
                </el-row>
                <el-row>
                  <!--
                    <el-col :span="12">
                      <el-form-item label="登录密码：" prop="passWord">
                        <el-input placeholder="请输入登录密码" onKeyUp="value=value.replace(/[\W]/g,'')"
                                v-model="form.passWord" show-password></el-input>
                      </el-form-item>
                    </el-col>
                    -->
                    <el-col :span="12">
                        <el-form-item label="立档单位编码：" prop="tenantCode">
                            <el-input v-model="form.tenantCode" :disabled="isDisabled"
                                onKeyUp="value=value.replace(/[\W]/g,'')" @blur="salaryChange" placeholder="请输入立档单位编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12"> <el-form-item label="全宗号：" prop="fondsCode">
                      <el-input v-model="form.fondsCode" placeholder="请输入全宗号" :disabled="qzhIsDisabled"/>
                      </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="描述：" prop="remark">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入描述" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="状态：">
                            <el-radio-group v-model="form.state">
                                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                                    :label="dict.value">{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>



            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
<!--                    <div class="el-upload__tip" slot="tip">-->
<!--                        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
<!--                    </div>-->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                        @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listTENANT, addTENANT, getTENANT, updateTENANT, delTENANT, changeTENANTStatus } from "@/api/manage/infoManage";
import { getToken } from "@/utils/auth";
import estimateTableHeight from '@/mixins/estimateTableHeight'//vue项目中element-tabel自动计算高度
export default {
    name: "Role",
    dicts: ['sys_normal_disable'],
    mixins: [estimateTableHeight], // 混入方法
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 立档单位列表表格数据
            tenantList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                userName: undefined,
            },
            // 表单参数
            form: {},
            //立档单位编码：添加可以编辑，修改时禁止编辑
            isDisabled: false,
            //全宗号：添加可以编辑，修改时禁止编辑
            qzhIsDisabled: false,
            // /^[a-zA-Z][^\u3400-\u9FFF]*$/
            // 表单校验
            rules: {
                registeredUnit: [
                    { required: true, message: "请输入注册单位", trigger: "blur" }
                ],
                registeredPerson: [
                    { required: true, message: "请输入注册人", trigger: "blur" }
                ],
                userName: [
                    { required: true, message: "请输入用户名", trigger: "blur" }
                ],
                fondsCode: [
                    { required: true, message: "请输入全宗号", trigger: "blur" }
                ],
                // passWord: [
                //     { required: true, message: "请输入密码", trigger: "blur" }
                // ],
                isManagerDept: [
                  { required: true, message: "请选择" }
                ],
                tenantCode: [
                    { required: true, message: "请输入立档单位编码", trigger: "blur" },
                    //{ required: true, pattern: /^[A-Z][^\u3400-\u9FFF]*$/, message: "立档单位编码不能是中文且必须以大写英文字母开头", trigger: "blur" }
                    { required: true, pattern: /^[A-Z]+$/, message: "立档单位编码只能输入大写英文字母", trigger: "blur" }
                ]
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/manage/tenant/importData"
            },
        };
    },
    created() {
        this.getList();
        console.log(this.dict.type.sys_normal_disable)
    },
    methods: {

        //解决vue+element— el-input 限制只能输入数字时和字母时与表单验证rules冲突问题
        salaryChange(e) {
            this.form.tenantCode = e.target.value;
        },
        /** 查询立档单位列表 */
        getList() {
            this.loading = true;
            listTENANT(this.queryParams).then(response => {
                this.tenantList = response.rows;
                this.total = response.total;
                this.loading = false;
            }
            );
        },

        // 立档单位信息状态修改
        handleStatusChange(row) {
            console.log(row)
            let text = row.state === "0" ? "启用" : "停用";
            this.$modal.confirm('确认要"' + text + '""' + row.userName + '"立档单位吗？').then(function () {
                return changeTENANTStatus(row.id, row.state);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.state = row.state === "0" ? "1" : "0";
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                registeredUnit: null,
                registeredPerson: null,
                userName: null,
                loginName: null,
                passWord: null,
                remark: null,
                tenantCode: null,
                fondsCode: null,
                state: "1"   //1=关闭，0=开启
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            console.log(this.resetForm("queryForm"), "sdlfjlk")
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.roleId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },

        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            console.log('hahaha');
            this.rules.tenantCode = [
              { required: true, message: "请输入立档单位编码", trigger: "blur" },
              //{ required: true, pattern: /^[A-Z][^\u3400-\u9FFF]*$/, message: "立档单位编码不能是中文且必须以大写英文字母开头", trigger: "blur" }
              { required: true, pattern: /^[A-Z]+$/, message: "立档单位编码只能输入大写英文字母", trigger: "blur" }
            ]
            this.open = true;
            this.isDisabled = false;
            this.qzhIsDisabled = false;
            this.title = "添加立档单位信息";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const ID = row.id || this.ids
            console.log('hehehe');
            this.rules.tenantCode = null;
            getTENANT(ID).then(response => {
                this.form = response.data;
                this.state = parseInt(response.data.state);
                this.open = true;
                this.isDisabled = true;
                this.qzhIsDisabled = true;
                this.title = "修改立档单位信息";
            });
        },

        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != undefined) {
                        updateTENANT(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {

                        addTENANT(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const ID = row.id || this.ids;
            this.$modal.confirm('是否确认删除所选数据项？').then(function () {
                return delTENANT(ID);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('/manage/tenant/export', {
                ...this.queryParams
            }, `infoManage_${new Date().getTime()}.xlsx`)
        },
        /**导入按钮操作 */
        handleImport() {
            this.upload.title = "立档单位信息导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('/manage/tenant/importTemplate', {
            }, `infoManage_template_${new Date().getTime()}.xlsx`)
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        }
    }
};
</script>
<style lang="scss" scoped></style>
